package it.valeandre.omino.fragment;

import it.valeandre.omino.R;
import it.valeandre.omino.model.Setting;
import it.valeandre.omino.model.TeamsList;
import it.valeandre.omino.net.NetworkService;
import it.valeandre.omino.net.NetworkServiceListener;
import it.valeandre.omino.utils.Utils;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class SettingsSlidingFragment extends UpgradableBaseFragment {
	public static final String TAG = "SettingsSlidingFragment";
	private View mContentView;
	private String[] mTeams;
	// private boolean mSettingPushFlag;
	// private int mCounter;
	private boolean mError;
	protected ArrayList<String> mSelectedTeams = new ArrayList<String>();
	private AlertDialog mTeamsDialog;
	private CheckBox mCheckBox;
	private Setting mSettings;
	private TextView mTeamsListText;
	private Setting mOldSettings;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	private void initCheckBox() {
		mCheckBox = (CheckBox) mContentView.findViewById(R.id.checkBox1);
		
		boolean error = false;
		boolean pushFlag = false;
		if (mSettings == null) {
			error = true;
		} else {
			if (mSettings.getFlagPush().getValue().equals("false"))
				pushFlag = true;
			if (mSettings.getFlagPush().getValue().equals("true"))
				pushFlag = false;
		}
		
		mCheckBox.setEnabled(!getInterFragmentInterface().isGCMRegistrationError() && !error);
		mCheckBox.setChecked(pushFlag);
	}

	public void resetSelectedTeams() {
		if (mSettings != null) {
			mSelectedTeams = (ArrayList<String>) mSettings.getTeamsList();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		mContentView = inflater.inflate(R.layout.fragment_settings, null);
		// mSettingPushFlag = getInterFragmentInterface().getSettingPushFlag();
		mTeamsListText = (TextView)mContentView.findViewById(R.id.settings_team_list);
		mSettings = getInterFragmentInterface().getSettings();
		mOldSettings = mSettings;
		initSpinner();

		initCheckBox();

		initOkButton();

		Button exit = (Button) mContentView.findViewById(R.id.exit_button);
		exit.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// dismiss();
				getInterFragmentInterface().getSlider().animateClose();
//				resetSelectedTeams();
				undoUnsavedOperations();
			}
		});
		resetSelectedTeams();
		updateTeamsListText();

		return mContentView;
	}

	private void initOkButton() {
		Button okButton = (Button) mContentView.findViewById(R.id.bottone_socetta);
		okButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				performOk();
			}

		});
		boolean error = false;
		if (getInterFragmentInterface().getSettings() == null) {
			error = true;
		}
		okButton.setEnabled(!getInterFragmentInterface().isGCMRegistrationError() && !error);
		// okButton.setEnabled(!getInterFragmentInterface().isGCMRegistrationError());
	}

	private void performOk() {
		sendCheck(!mCheckBox.isChecked());
	}

	private void sendCheck(boolean pushEnabled) {
		Utils.log("i", "sendCheck pushEnabled = " + pushEnabled);
		getInterFragmentInterface().showProgress();
		Context context = getActivity();
		String deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
		String registrationId = Utils.readRegisteredToken(context);
		NetworkService.getInstance().setPushEnabled(pushEnabled, registrationId, deviceId, new NetworkServiceListener() {

			@Override
			public void setPushEnabledPerformed(final boolean enabled) {
				Utils.log("i", "setPushEnabledPerformed, value = " + enabled);
				mError = false;
				mHandler.post(new Runnable() {
					public void run() {
						String teamsListString = "";
						if (mSelectedTeams != null && mSelectedTeams.size() > 0) {
							for (String team : mSelectedTeams) {
								teamsListString = teamsListString.concat(" " + team);
							}
						} else {
							if(mTeams != null && mTeams.length > 0 /*&& enabled*/) {
								for(String team: mTeams) {
									teamsListString = teamsListString.concat(" " + team);
								}
							}
						}
						sendTeams(teamsListString);
					}
				});
				getInterFragmentInterface().setSettingPushFlag(enabled);
				
			}

			@Override
			public void setPushEnabledFailed(int statusCode) {
				mError = true;
				// mCounter--;
				mHandler.post(new Runnable() {
					public void run() {
						// if (mCounter == 0) {
						reloadSettings();
						showToast(mError);
						// }
					}
				});
				Utils.log("e", "setPushEnabledFailed: " + statusCode);
			}

			@Override
			public void setPushEnabledFailed(Exception e) {
				mError = true;
				// mCounter--;
				mHandler.post(new Runnable() {
					public void run() {
						// if (mCounter == 0) {
						reloadSettings();
						showToast(mError);
						// }
					}
				});
				Utils.log("e", "setPushEnabledFailed: " + e.getMessage());
			}

		});

	}

	private void sendTeams(String teamsListString) {
		Utils.log("i", "sendTeams: teamsString = " + teamsListString);
		Context context = getActivity();
		String deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
		String registrationId = Utils.readRegisteredToken(context);
		NetworkService.getInstance().setPushTeams(teamsListString.trim(), deviceId, registrationId, new NetworkServiceListener() {

			@Override
			public void setPushTeamsPerformed(String teamsListString) {
				Utils.log("d", "setPushTeamsPerformed: " + teamsListString);
				mError = false;
				mHandler.post(new Runnable() {

					public void run() {
						showToast(mError);
						reloadSettings();
					}
				});
			}

			@Override
			public void setPushTeamsFailed(int statusCode) {
				Utils.log("e", "setPushTeamsFailed: status = " + statusCode);
				mError = true;
				mHandler.post(new Runnable() {

					public void run() {
//						showToast(mError);
						reloadSettings();
					}
				});
			}

			@Override
			public void setPushTeamsFailed(Exception e) {
				Utils.log("e", "setPushTeamsFailed: " + e.getMessage());
				mError = true;
				mHandler.post(new Runnable() {

					public void run() {
//						showToast(mError);
						reloadSettings();
					}
				});
			}

		});
	}
	
	private void reloadSettings() {
		getInterFragmentInterface().loadSettings(false, new Observer() {
			
			public void update(Observable observable, Object data) {
				mSettings = (Setting)data;
				mOldSettings = mSettings;
				mHandler.post(new Runnable() {
					
					public void run() {
						refresh();
						updateTeamsListText();
						getInterFragmentInterface().hideProgress();
						getInterFragmentInterface().getSlider().animateClose();
					}
				});
			}
		});
	}

	private void showToast(boolean error) {
		if (error) {
			Toast.makeText(getActivity(), "Errore durante il salvataggio delle impostazioni, riprovare più tardi!", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(getActivity(), "Impostazioni salvate correttamente!", Toast.LENGTH_SHORT).show();
		}
	}

	private void initSpinner() {

		Button chooseTeams = (Button) mContentView.findViewById(R.id.fragment_settings_choose_button);
		chooseTeams.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				TeamsList teamsList = getInterFragmentInterface().getTeams();
				if (teamsList != null && teamsList.getTeams() != null && teamsList.getTeams().size() > 0) {
					showSelectTeamsDialog();
				} else {
					getTeams();
				}
			}
		});
		
		boolean error = false;
		if (getInterFragmentInterface().getSettings() == null) {
			error = true;
		}
		chooseTeams.setEnabled(!getInterFragmentInterface().isGCMRegistrationError() && !error);

	}

	@Override
	public void refresh() {
		mSettings = getInterFragmentInterface().getSettings();
		resetSelectedTeams();
		initCheckBox();
		initOkButton();
		initSpinner();
		updateTeamsListText();
	}

	private void showSelectTeamsDialog() {
		boolean[] checkedTeams = new boolean[mTeams.length];

		for (int i = 0; i < mTeams.length; i++) {
			checkedTeams[i] = mSelectedTeams.contains(mTeams[i]);
		}

		DialogInterface.OnMultiChoiceClickListener teamsDialogListener = new DialogInterface.OnMultiChoiceClickListener() {

			public void onClick(DialogInterface dialog, int wich, boolean isChecked) {
				if (isChecked) {
					mSelectedTeams.add(mTeams[wich]);
				} else {
					mSelectedTeams.remove(mTeams[wich]);
				}
				updateTeamsListText();
			}
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(getActivity().getResources().getString(R.string.settings_button_choose_teams));
		builder.setMultiChoiceItems(mTeams, checkedTeams, teamsDialogListener).setNegativeButton(getActivity().getResources().getString(R.string.ok), null);

		mTeamsDialog = builder.create();
		mTeamsDialog.show();
	}
	
	private void updateTeamsListText() {
		
		if (getInterFragmentInterface().isGCMRegistrationError() || getInterFragmentInterface().getSettings() == null) {
			mTeamsListText.setTextColor(getActivity().getResources().getColor(R.color.grey_text_disabled));
			mTeamsListText.setText(getActivity().getResources().getString(R.string.unavailable));
			return;
		}
		
		if(mCheckBox.isChecked()) {
			mTeamsListText.setTextColor(getActivity().getResources().getColor(R.color.red_italy));
			updateTeamsListText(getActivity().getResources().getString(R.string.push_disabled));
		} else {
			mTeamsListText.setTextColor(getActivity().getResources().getColor(R.color.green_italy));
			if(mSelectedTeams != null && mSelectedTeams.size()>0 && mSelectedTeams.size() != 20) {
				String text = mSelectedTeams.get(0);
				for(int i=1; i<mSelectedTeams.size(); i++ ) {
					text = text.concat(", " + mSelectedTeams.get(i));
				}
				mTeamsListText.setText(text);
			} else {
				updateTeamsListText(getActivity().getResources().getString(R.string.all_teams));
			}
		}
	}

	private void updateTeamsListText(String text) {
		if(mTeamsListText != null) {
			mTeamsListText.setText(text);
		}
	}
	
	public void getTeams() {
		getInterFragmentInterface().showProgress();

		getInterFragmentInterface().loadTeams(false, new Observer() {

			public void update(Observable observable, Object data) {
				if (data != null) {
					TeamsList teamsList = (TeamsList) data;
					mTeams = new String[teamsList.getTeams().size()];
					for (int i = 0; i < teamsList.getTeams().size(); i++) {
						mTeams[i] = teamsList.getTeams().get(i).getValue();
					}
					mHandler.post(new Runnable() {

						public void run() {
							showSelectTeamsDialog();
						}
					});
				} else {
					mHandler.post(new Runnable() {

						public void run() {
							getInterFragmentInterface().showDialog(getActivity().getResources().getString(R.string.connection_alert));

						}
					});
				}
			}
		});

	}
	
	public void undoUnsavedOperations() {
		mSettings = mOldSettings;
		initCheckBox();
		initOkButton();
		resetSelectedTeams();
		updateTeamsListText();
	}

}
